package com.lubase.metadata.tabletrigger;

import com.lubase.model.DbEntity;
import com.lubase.model.DbTable;
import com.lubase.model.EDBEntityState;
import com.lubase.orm.QueryOption;
import com.lubase.orm.TableFilter;
import com.lubase.orm.extend.ITableTrigger;
import com.lubase.model.DbCollection;
import com.lubase.orm.operate.EOperateMode;
import com.lubase.orm.service.DataAccess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MsDatabaseTrigger implements ITableTrigger {

    /**
     * 1: 生产主库  2：生产备库  3：测试环境
     */
    @Value("${custom.metadata-database-environment}")
    private String metadataDatabaseEnvironment;
    @Autowired
    DataAccess dataAccess;

    @Override
    public void afterUpdate(DbTable tableInfo, DbEntity entity, Boolean isServer) throws Exception {
        if (entity.getDataState().equals(EDBEntityState.Added)) {
            // 将数据库连接信息同步到数据源表
            QueryOption queryOption = new QueryOption("ms_database_info");
            queryOption.setTableFilter(new TableFilter("ms_database_id", entity.getId(), EOperateMode.Equals));
            DbCollection coll = dataAccess.queryAllData(queryOption);
            for (DbEntity dbEntity : coll.getData()) {
                if (dbEntity.get("env_info").toString().equals(metadataDatabaseEnvironment)) {
                    coll = dataAccess.getEmptyData("ms_database");
                    entity.put("database_code", dbEntity.get("database_code"));
                    entity.put("host", dbEntity.get("host"));
                    entity.put("port", dbEntity.get("port"));
                    entity.put("user_name", dbEntity.get("user_name"));
                    entity.put("password", dbEntity.get("password"));
                    entity.put("instance_name", dbEntity.get("instance_name"));
                    entity.setState(EDBEntityState.Modified);
                    coll.getData().add(entity);
                    coll.setEnableTableTrigger(false);
                    dataAccess.update(coll);
                }
            }
        }
    }

    @Override
    public String getTriggerTableCode() {
        return "ms_database";
    }

    @Override
    public String getTriggerName() {
        return "ms_database";
    }

    @Override
    public Boolean isAdd() {
        return true;
    }
}
